package com.kude.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import net.sf.json.util.PropertyFilter;

import com.kude.entity.ArticleCategory;
import com.kude.entity.ArticleCategoryPrefix;
import com.kude.entity.ProductCategory;
import com.kude.manager.OperException;
import com.kude.service.ArticleCategoryPrefixService;
import com.kude.service.ArticleCategoryService;
import com.kude.util.BeanFactory;

public class GetSubArticleCategoryServlet extends HttpServlet {
	public ArticleCategoryService articleCategoryService;
	public ArticleCategoryPrefixService articleCategoryPrefixService;
	/**
	 * Constructor of the object.
	 */
	public GetSubArticleCategoryServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		this.doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		
		articleCategoryService = BeanFactory.getBean(ArticleCategoryService.class.getName());
		articleCategoryPrefixService = BeanFactory.getBean(ArticleCategoryPrefixService.class.getName());
		String operation = request.getParameter("operation");
		
		if (operation.equals("add")) {
			try {
				this.add(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("update")) {
			try {
				this.update(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("delete")) {
			try {
				this.delete(request, response);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		if (operation.equals("getArticleCategoryByPrefix")) {
			try {
				this.getArticleCategoryByPrefix(request, response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (operation.equals("getArticleCategoryByParentId")) {
			try {
				this.getArticleCategoryByParentId(request, response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (operation.equals("getArticleCategoryByParentId2")) {
			try {
				this.getArticleCategoryByParentId2(request, response);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private void getArticleCategoryByParentId(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int id = Integer.parseInt(request.getParameter("parentId"));
		JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String name, Object value) {
                if (name.equals("articleCategoryPrefix")||name.equals("articleCategory")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
		JSONArray productCategoryList = JSONArray
				.fromObject(articleCategoryService.getArticleCategoryListByParentId(id),config);
		
		int total = articleCategoryService.getTotalByParentId(id);
		StringBuilder result = new StringBuilder();
		result.append("{\"total\":" + total + ",\"rows\":");
		result.append(productCategoryList.toString());
		result.append("}");
		
		response.getWriter().write(result.toString());
		response.getWriter().flush();
		
	}
	
	private void getArticleCategoryByParentId2(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		int id = Integer.parseInt(request.getParameter("parentId"));
		JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String name, Object value) {
                if (name.equals("articleCategoryPrefix")||name.equals("articleCategory")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
		JSONArray productCategoryList = JSONArray
				.fromObject(articleCategoryService.getArticleCategoryListByParentId(id),config);
		
		StringBuilder result = new StringBuilder();
		result.append(productCategoryList.toString());
		
		response.getWriter().write(result.toString());
		response.getWriter().flush();
		
	}

	private void getArticleCategoryByPrefix(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String prefix = request.getParameter("prefix");
		JsonConfig config = new JsonConfig();
        config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
        config.setJsonPropertyFilter(new PropertyFilter() {
            public boolean apply(Object source, String name, Object value) {
                if (name.equals("articleCategoryPrefix")||name.equals("articleCategory")) {
                    return true;
                } else {
                    return false;
                }
            }
        });
		JSONArray articleCategoryList = JSONArray
				.fromObject(articleCategoryService.getArticleCategoryListByPrefix(prefix),config);
		response.getWriter().write(articleCategoryList.toString());
		response.getWriter().flush();
		
	}

	private void delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		int id = Integer.parseInt(request.getParameter("id"));
		try {
			articleCategoryService.deleteArticleCategory(id);
			response.getWriter().write("1");
			response.getWriter().flush();
		} catch (OperException e) {
			response.getWriter().write("0");
			response.getWriter().flush();
		}		
	}

	private void update(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			int articleCategoryId = Integer.parseInt(request.getParameter("articleCategoryId"));
			int prefixId = Integer.parseInt(request.getParameter("prefixId"));
			String categoryName = request.getParameter("categoryName");
			
			ArticleCategory articleCategory = articleCategoryService.getArticleCategory(articleCategoryId);
			ArticleCategoryPrefix a = articleCategoryPrefixService.getArticleCategoryPrefix(prefixId);
			articleCategory.setCategoryName(categoryName);
			articleCategory.setPrefix(a.getPrefix() + categoryName);
			
			// TODO 把需要更新的字段更新
			articleCategoryService.updateArticleCategory(articleCategory);
			response.getWriter().write("1");
			response.getWriter().flush();
		} catch (OperException e) {
			response.getWriter().write("0");
			response.getWriter().flush();
		}
		
	}

	private void add(HttpServletRequest request, HttpServletResponse response) throws Exception {
		try {
			ArticleCategory articleCategory = new ArticleCategory();
			String categoryName = request.getParameter("categoryName");
			int prefixId = Integer.parseInt(request.getParameter("prefixId"));
			ArticleCategoryPrefix a = articleCategoryPrefixService.getArticleCategoryPrefix(prefixId);
			
			articleCategory.setArticleCategoryPrefix(a);
			articleCategory.setCategoryName(categoryName);
			articleCategory.setPrefix(a.getPrefix() + categoryName);
			// TODO 把需要更新的字段更新
			articleCategoryService.addArticleCategory(articleCategory);
			response.getWriter().write("1");
			response.getWriter().flush();
		} catch (OperException e) {
			response.getWriter().write("0");
			response.getWriter().flush();
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
